package com.sfzlot.dev.netty.server.client;


import com.sfzlot.dev.netty.server.client.handler.ClientHandler;
import com.sfzlot.dev.netty.server.server.decode.Decoder;
import com.sfzlot.dev.netty.server.server.encode.Encoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;


/**
 * Created by ASUS on 2017/5/27.
 */
public class Client extends Thread{
	public static String server = "127.0.0.1";
	public static int port = 17650;
	
    public void connect(int port,String host) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY,true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                        	socketChannel.pipeline().addLast(new Decoder(1024, 28, 2, 0, 0, false));
                        	socketChannel.pipeline().addLast(new Encoder());
                        	socketChannel.pipeline().addLast(new ClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host,port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    
    
    @Override
	public void run() {
    	 try {
    		 while(true){
    			 Client client = new Client();
    			 client.connect(port,server);
    		 }
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
	}



	public static void main(String[] args) {
		try {
			new Client().connect(port,server);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
